package com.buildings.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.buildings.R;
import com.buildings.activity.FormListActivity;
import com.buildings.activity.TaskMapActivity;
import com.buildings.activity.map.ReinforceFormListActivity;
import com.buildings.activity.map.ReinforceMapActivity;
import com.buildings.adapter.TaskListAdapter;
import com.buildings.api.Api;
import com.buildings.bean.TaskBean;
import com.buildings.bean.TaskListBean;
import com.buildings.http.BaseCallBack;
import com.buildings.http.MyHttpClient;
import com.buildings.util.CustomToast;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;

/**
 *任务列表
 */

public class TaskListFragment extends Fragment {
    private RecyclerView recyclerView;
    private SmartRefreshLayout refreshLayout;
    private RelativeLayout no_data_layout;
    private String type;
    private TaskListAdapter mAdapter;
    private List<TaskBean> data;
    private int pageNum = 1;//当前请求页数
//    private int pageCount = 1;//总页数
    private int pageSize = 15;
//    private int pageSize;
    private int total;//
    private Dialog dialog;



    public static TaskListFragment newInstance(String type) {
        TaskListFragment fragment = new TaskListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type",type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_task_list, container, false);
    }
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        showAdapter();
        initData();

    }

    private void initView(View view){
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        refreshLayout = view.findViewById(R.id.refreshLayout);
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if(data.size() >= total){
                    CustomToast.showToast(getActivity(),"没有更多的任务");
                    refreshlayout.finishLoadmore();
                }else {
                    http(type);
                }
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 1;
                http(type);
            }
        });
    }

    private void initData(){
        type = getArguments().getString("type");
        if(type == null){
            type = "";
        }
        http(type);

//        Gson gson = new Gson();
//        String str = "{\"code\":200,\"data\":{\"total\":2,\"rows\":[{\"taskId\":\"1\",\"taskNum\":\"1\",\"taskName\":\"312\",\"taskType\":\"0\",\"taskManager\":null,\"groupId\":null,\"groupLeader\":null,\"groupLeaderMobile\":null,\"mapInfo\":\"116.40358,39.87034;116.40429,39.86978;116.40575,39.87005\",\"status\":\"1\",\"createUser\":null,\"createTime\":null,\"updateUser\":null,\"updateTime\":null,\"delFlag\":\"1\"},{\"taskId\":\"2\",\"taskNum\":\"1\",\"taskName\":\"2121221212121212121212121212121212121212121212121212121212121212121212\",\"taskType\":\"0\",\"taskManager\":null,\"groupId\":null,\"groupLeader\":null,\"groupLeaderMobile\":null,\"mapInfo\":\"112.07975,37.24256;112.08061,37.23637;112.09297,37.23767;112.09199,37.24437;112.09194,37.24443;112.09194,37.24437\",\"status\":\"2\",\"createUser\":null,\"createTime\":null,\"updateUser\":null,\"updateTime\":null,\"delFlag\":\"1\"}],\"message\":\"查询成功\"},\"message\":null}";
//        TaskListBean a = gson.fromJson(str,TaskListBean.class);
//        List<TaskBean> result = a.getData().getRows();
//        data.addAll(result);
//        update();
    }


    private void showAdapter() {
        data = new ArrayList<>();

//        LinearLayoutManager linerLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//        recyclerView.addItemDecoration( new DividerGridItemDecoration(getActivity() ));
        recyclerView.addItemDecoration( new DividerItemDecoration(getActivity(),LinearLayoutManager.VERTICAL));
        mAdapter = new TaskListAdapter(getActivity(),data);
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new TaskListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                TaskBean bean = data.get(position);
                String status = bean.getStatus();//2 已完成
                Intent intent = new Intent();
                if (bean.getTaskType().equals("2")){
                    intent.setClass(getActivity(), ReinforceMapActivity.class);
                }else {
                    intent.setClass(getActivity(), TaskMapActivity.class);

                }
                intent.putExtra("mapInfo",bean.getMapInfo());
                intent.putExtra("taskId",bean.getTaskId());
                intent.putExtra("taskName",bean.getTaskName());
                intent.putExtra("status",status);
                startActivity(intent);

            }
            @Override
            public void onItemLongClick(View view, final int position) {

            }

            @Override
            public void onTask(View view, int position) {
                TaskBean bean = data.get(position);
                Intent intent = new Intent();
                if (bean.getTaskType().equals("2")){
                    intent.setClass(getActivity(), ReinforceMapActivity.class);
                }else {
                    intent.setClass(getActivity(), TaskMapActivity.class);

                }
                intent.putExtra("mapInfo",bean.getMapInfo());
                intent.putExtra("taskId",bean.getTaskId());
                intent.putExtra("taskName",bean.getTaskName());
                startActivity(intent);
            }

            @Override
            public void onForm(View view, int position) {
                TaskBean bean = data.get(position);
                String status = bean.getStatus();//2 已完成
                Intent intent = new Intent(getActivity(),FormListActivity.class);
                if (bean.getTaskType().equals("2")){
                    intent.setClass(getActivity(), ReinforceFormListActivity.class);
                }else {
                    intent.setClass(getActivity(), FormListActivity.class);
                }
                intent.putExtra("taskId",bean.getTaskId());
                intent.putExtra("taskName",bean.getTaskName());
                intent.putExtra("status",status);
                startActivity(intent);

//                TaskBean taskBean = data.get(position);
//                switch (taskBean.getType()){
//                    case 1:
//                        startActivity(new Intent(getActivity(),TownHouseFormActivity.class));
//                        break;
//                    case 2:
//                        startActivity(new Intent(getActivity(),TownNonHouseFormActivity.class));
//                        break;
//                    case 3:
//                        startActivity(new Intent(getActivity(),VillageHouseFormActivity.class));
//                        break;
//                    case 4:
//                        startActivity(new Intent(getActivity(),VillagePublicFormActivity.class));
//                        break;
//                    default:
//                        startActivity(new Intent(getActivity(),TownHouseFormActivity.class));
//                        break;
//                }


            }
        });
    }


    private void update(){
        mAdapter.update(data);
    }

    private void http(String type){

        /*
        @RequestParam("type") String type,@RequestParam("curtPage") int curtPage,@RequestParam("pageSize") int pageSize
         */
        //type 未完成1   已完成2
        String url = Api.TASK_LIST+"?type="+type+"&curtPage="+pageNum+"&pageSize="+pageSize;
//        try {
//            url = URLEncoder.encode(url,"UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        JsonBuilder jsonBuilder = new JsonBuilder(getActivity());
//        jsonBuilder.put("pageNum",pageNum);
//        jsonBuilder.put("type",type);
        MyHttpClient
                .newBuilder()
                .get()
                .url(url)
//                .addParam(jsonBuilder.toJsonString())
                .build()
                .enqueue(new BaseCallBack<TaskListBean>() {
                    @Override
                    public void onSuccess(TaskListBean bean) {
                        super.onSuccess(bean);
                        refreshLayout.finishLoadmore();
                        refreshLayout.finishRefresh();
                        if(bean != null && bean.getCode() == 200){
                            if(pageNum == 1){
                                data.clear();
                            }
                            total = bean.getData().getTotal();
                            List<TaskBean> result = bean.getData().getRows();
                            data.addAll(result);
                            update();
                            pageNum++;
                        }else {
                            CustomToast.showToast(getActivity(),"获取失败");
                        }
                        if (dialog != null)
                            dialog.dismiss();

                    }
                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                CustomToast.showToast(getActivity(),"网络异常");
                            }
                        });
                        refreshLayout.finishLoadmore();
                        refreshLayout.finishRefresh();
                        if (dialog != null)
                            dialog.dismiss();
                    }
                });

    }

}
